package org.finesys.ai.core;

import okhttp3.Interceptor;
import okhttp3.Request.Builder;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

class GenericHeaderInjector implements Interceptor {
    private final Map<String, String> headers = new HashMap<>();

    /**
     * GenericHeaderInjector 构造函数
     *
     * @param headers 包含自定义头信息的Map
     */
    GenericHeaderInjector(Map<String, String> headers) {
        Optional.ofNullable(headers)
                .ifPresent(this.headers::putAll);
    }

    /**
     * 拦截请求并添加自定义头信息
     *
     * @param chain 请求链
     * @return 响应
     * @throws IOException 如果处理请求时发生I/O错误
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        Builder builder = chain.request().newBuilder();

        // Add headers
        this.headers.forEach(builder::addHeader);

        return chain.proceed(builder.build());
    }
}
